import 'dart:io';
import 'dart:ui';

import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:video_player/video_player.dart';
import '../../core/widgets/report_dialog.dart';
import '../../core/widgets/toast_notifications.dart';

/// 本地视频播放页面
class VamosLocalVideoPlayerInterface extends StatefulWidget {
  final String videoPath;
  final String title;
  final String description;

  const VamosLocalVideoPlayerInterface({
    super.key,
    required this.videoPath,
    required this.title,
    required this.description,
  });

  @override
  State<VamosLocalVideoPlayerInterface> createState() =>
      _VamosLocalVideoPlayerInterfaceState();
}

class _VamosLocalVideoPlayerInterfaceState
    extends State<VamosLocalVideoPlayerInterface> {
  late VideoPlayerController _controller;
  bool _isInitialized = false;
  bool _isPlaying = false;
  bool _showControls = true;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _initializeVideo();
  }

  /// 初始化视频
  Future<void> _initializeVideo() async {
    try {
      _controller = VideoPlayerController.file(File(widget.videoPath));
      await _controller.initialize();

      if (mounted) {
        setState(() {
          _isInitialized = true;
          _isLoading = false;
        });

        // 自动播放
        _controller.play();
        setState(() {
          _isPlaying = true;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        ToastNotificationHelper.showErrorToast(
          context,
          message: 'Failed to load video',
        );
      }
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Stack(
          children: [
            // 视频播放器
            _buildVideoPlayer(),

            // 顶部控制栏
            _buildTopControls(),

            // 底部控制栏
            _buildBottomControls(),

            // 加载指示器
            if (_isLoading) _buildLoadingIndicator(),

            // 错误提示
            if (!_isLoading && !_isInitialized) _buildErrorWidget(),
          ],
        ),
      ),
    );
  }

  /// 构建视频播放器
  Widget _buildVideoPlayer() {
    if (!_isInitialized) {
      return Container(
        width: double.infinity,
        height: double.infinity,
        color: Colors.black,
        child: Center(
          child: Icon(
            Icons.play_circle_outline,
            size: 80.w,
            color: Colors.white.withOpacity(0.5),
          ),
        ),
      );
    }

    return GestureDetector(
      onTap: _toggleControls,
      child: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: AspectRatio(
          aspectRatio: _controller.value.aspectRatio,
          child: VideoPlayer(_controller),
        ),
      ),
    );
  }

  /// 构建顶部控制栏
  Widget _buildTopControls() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: AnimatedOpacity(
        opacity: _showControls ? 1.0 : 0.0,
        duration: Duration(milliseconds: 300),
        child: Container(
          padding: EdgeInsets.only(
            top: MediaQuery.of(context).padding.top + 16.h,
            left: 16.w,
            right: 16.w,
            bottom: 16.h,
          ),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Colors.black.withOpacity(0.7), Colors.transparent],
            ),
          ),
          child: Row(
            children: [
              // 返回按钮
              Container(
                width: 40.w,
                height: 40.w,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.arrow_back_ios,
                  color: Colors.white,
                  size: 20.w,
                ).center().inkWell(onTap: () => Navigator.pop(context)),
              ),

              SizedBox(width: 16.w),

              // 标题
              Expanded(
                child: Text(
                  widget.title,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w600,
                        ).fontFamily,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),

              SizedBox(width: 16.w),

              // 举报按钮
              Container(
                width: 40.w,
                height: 40.w,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  shape: BoxShape.circle,
                ),
                child: Image.asset(
                  'assets/images/report.png',
                  width: 20.w,
                  height: 20.w,
                ).center().inkWell(onTap: _handleVideoReport),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建底部控制栏
  Widget _buildBottomControls() {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: AnimatedOpacity(
        opacity: _showControls ? 1.0 : 0.0,
        duration: Duration(milliseconds: 300),
        child: Container(
          padding: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Colors.transparent, Colors.black.withOpacity(0.7)],
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 进度条
              if (_isInitialized) _buildProgressBar(),

              SizedBox(height: 16.h),

              // 控制按钮
              Row(
                children: [
                  // 播放/暂停按钮
                  Container(
                    width: 50.w,
                    height: 50.w,
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.5),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      _isPlaying ? Icons.pause : Icons.play_arrow,
                      color: Colors.white,
                      size: 24.w,
                    ).center().inkWell(onTap: _togglePlayPause),
                  ),

                  SizedBox(width: 16.w),

                  // 时间显示
                  if (_isInitialized) _buildTimeDisplay(),

                  Spacer(),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建进度条
  Widget _buildProgressBar() {
    return VideoProgressIndicator(
      _controller,
      allowScrubbing: true,
      colors: VideoProgressColors(
        playedColor: Colors.white,
        bufferedColor: Colors.white.withOpacity(0.3),
        backgroundColor: Colors.white.withOpacity(0.1),
      ),
    );
  }

  /// 构建时间显示
  Widget _buildTimeDisplay() {
    final duration = _controller.value.duration;
    final position = _controller.value.position;

    return Text(
      '${_formatDuration(position)} / ${_formatDuration(duration)}',
      style: TextStyle(
        color: Colors.white,
        fontSize: 12.sp,
        fontFamily: GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
      ),
    );
  }

  /// 构建加载指示器
  Widget _buildLoadingIndicator() {
    return Center(
      child: Container(
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.7),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(color: Colors.white, strokeWidth: 2.w),
            SizedBox(height: 16.h),
            Text(
              'Loading video...',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建错误组件
  Widget _buildErrorWidget() {
    return Center(
      child: Container(
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.7),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.error_outline, color: Colors.red, size: 48.w),
            SizedBox(height: 16.h),
            Text(
              'Failed to load video',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w600).fontFamily,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              'Please check if the video file exists',
              style: TextStyle(
                color: Colors.white.withOpacity(0.7),
                fontSize: 12.sp,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
              ),
            ),
            SizedBox(height: 16.h),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Text(
                'Retry',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 14.sp,
                  fontFamily:
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w600,
                      ).fontFamily,
                ),
              ).inkWell(
                onTap: () {
                  setState(() {
                    _isLoading = true;
                  });
                  _initializeVideo();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 切换控制栏显示
  void _toggleControls() {
    setState(() {
      _showControls = !_showControls;
    });
  }

  /// 切换播放/暂停
  void _togglePlayPause() {
    if (_isPlaying) {
      _controller.pause();
    } else {
      _controller.play();
    }
    setState(() {
      _isPlaying = !_isPlaying;
    });
  }

  /// 处理视频举报
  void _handleVideoReport() {
    showVamosReportDialog(
      context: context,
      title: 'Report Video',
      subtitle: 'Please select a reason for reporting this video.',
      onReportSubmitted: (VamosReportOption option) {
        ToastNotificationHelper.showSuccessToast(
          context,
          message: 'Video reported successfully',
        );
        Navigator.pop(context);
      },
    );
  }

  /// 格式化时间
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = duration.inHours;
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);

    if (hours > 0) {
      return '${twoDigits(hours)}:${twoDigits(minutes)}:${twoDigits(seconds)}';
    } else {
      return '${twoDigits(minutes)}:${twoDigits(seconds)}';
    }
  }
}
